package util;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class DatabaseUtil {
    private static HikariDataSource dataSource;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl("jdbc:mysql://localhost:3306/db_employees");
            config.setUsername("root");
            config.setPassword("root");

            // 连接池配置
            config.setMaximumPoolSize(20);          // 最大连接数
            config.setMinimumIdle(5);               // 最小空闲连接
            config.setConnectionTimeout(30000);     // 连接超时时间(ms)
            config.setIdleTimeout(600000);          // 空闲连接超时时间(ms)
            config.setMaxLifetime(1800000);         // 连接最大生命周期(ms)
            config.setAutoCommit(true);             // 自动提交

            dataSource = new HikariDataSource(config);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void closeConnection(Connection dataSource) throws SQLException {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
        }
    }
}
